<template>
    <div>
        <input 
            type="text" 
            v-bind="$attrs"
            v-model="selectedLabel"
            @focus="handleFocus"
        />
        <transition 
            name="le-zoom-in-top"
            @before-enter="handleMenuEnter"
            @after-leave="doDestroy">
            <le-select-menu 
                ref="popper"
                :append-to-body="popperAppendToBody"
                v-show="visible && emptyText !== false"
            >
                <le-option :value="query" created></le-option>
                <slot></slot>
            </le-select-menu>
        </transition>
    </div>
</template>

<script>
import Emitter from '../../mixins/emitter'
import LeSelectMenu from './le-select-dropdown.vue'
import LeOption from './le-option.vue'
import { getValueByPath,valueEquals } from '@/utils/util'
    export default {
        name: 'LeSelect',
        mixins: [ Emitter ],
        components: { LeSelectMenu,LeOption },
        provide() {
          return {
            'select': this
          };
        },
        data() {
            return {
                // 用于控制options的显示/隐藏的字段
                visible: false,
                selected: this.multiple ? [] : {},
                query: '',
                cachedOptions: [],
                createdLabel: null,
                createdSelected: false,
                selectedLabel: ''
            }
        },
        props: {
            value: {
              required: true
            },
            multiple: Boolean,
            popperAppendToBody: {
              type: Boolean,
              default: true
            },
            created: Boolean,
            valueKey: {
              type: String,
              default: 'value'
            },
        },
        watch: {
            // 观察options的
            visible(val) {
                if(!val) {
                   this.broadcast('LeSelectDropdown', 'destroyPopper');
                }else {
                   this.selectedLabel = this.selected.currentLabel;
                   this.broadcast('LeSelectDropdown', 'updatePopper');
                }
            },
        },
        computed: {
            emptyText() {
                return 'ABC';
            }
        },
        created() {
            this.$on('handleOptionClick', this.handleOptionSelect)
        },
        methods: {
            handleOptionSelect(option, byClick) {
                debugger
                this.$emit('input', option.value);
                this.emitChange(option.value);
                this.visible = false;
                console.log(byClick);
                
            },
             emitChange(val) {
                if (!valueEquals(this.value, val)) {
                this.$emit('change', val);
                }
            },
            getValueKey(item) {
                if (Object.prototype.toString.call(item.value).toLowerCase() !== '[object object]') {
                  return item.value;
                } else {
                  return getValueByPath(item.value, this.valueKey);
                }
            },
            handleFocus() {
                this.visible = true;
            },
            scrollToOption(option) {
                Array.isArray(option) && option[0]
            },
            // 鼠标移入 移入的时候触发option的选项展示
            handleMenuEnter() {
                this.$nextTick(() => this.scrollToOption(this.selected))
            },
            doDestroy() {
                // this.$refs.popper && this.$refs.popper.doDestroy();
            },
            getOption(value) {
                let option;
                const isObject = Object.prototype.toString.call(value).toLowerCase() === '[object object]';
                const isNull = Object.prototype.toString.call(value).toLowerCase() === '[object null]';
                const isUndefined = Object.prototype.toString.call(value).toLowerCase() === '[object undefined]';

                for (let i = this.cachedOptions.length -1; i >= 0; i--) {
                    const cacheOption = this.cachedOptions[i];
                    const isEqual = isObject 
                        ? getValueByPath(cacheOption.value, this.valueKey) === getValueByPath(value, this.valueKey)
                        : cacheOption.value === value;
                    if(isEqual) {
                        option = cacheOption;
                        break;
                    }
                }
                if(option) option;
                const label = (!isObject && !isNull && !isUndefined) ? String(value) : ''
                let newOption = {
                    value: value,
                    currentLabel: label
                }
                if(this.multiple) {
                    newOption.hitState = false;
                }
                return newOption;
            },
            setSelected() {
                if(!this.multiple) {
                    let option = this.getOption(this.value);
                    if(option.created) {
                        this.createdLabel = option.currentLabel;
                        this.createdSelected = true;
                    } else {
                        this.createdSelected = false;
                    }
                    this.selectedLabel = option.currentLabel;
                    this.selected = option;
                }
                let result = [];
                if (Array.isArray(this.value)) {
                    this.value.forEach(value => {
                        result.push(this.getOption(value));
                    });
                }
                this.selected = result;
                console.log(this.selected);
                // this.$nextTick(() => {
                //     this.resetInputHeight();
                // });
            }
        }
    }
</script>

<style lang="scss" scoped>
.el-zoom-in-top-enter-active,
.el-zoom-in-top-leave-active {
  opacity: 1;
  transform: scaleY(1);
  transform-origin: center top;
}
.el-zoom-in-top-enter,
.el-zoom-in-top-leave-active {
  opacity: 0;
  transform: scaleY(0);
}

</style>